﻿module Sustainalytics.GovernanceReports.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Routing = Sustainalytics.Routing;

    export class InsightAddController {

        //private currentInsight: GovernanceInsightDto;
        private governanceService: GovernanceService;
        private selectedFile: any;
        private oldFileName: string;
        private oldFileId: string;
        private newFileName: string;
        //disable save button until the pdf/image upload
        public isSaveDisabled: boolean;
        private $routeParams: any;

        public publicationDateOpen: boolean = false;

        constructor(
            private $scope: ICompanyControllerScope,
            private $modal: IModal,
            private $modalInstance: IModalInstance,
            private notificationFactory: Common.INotificationFactory,
            private staticObjectsAdmin: CommonAdmin.IStaticObjects,
            private RoutingService: Routing.IRoutingService,
            private currentInsight: GovernanceInsightDto,
            private companyProfile: GovernanceProfileDto,
            private companyName: string,
            GovernanceService) {

            var ctx = this;

            $scope['insightCompany'] = ctx;

            ctx.$routeParams = RoutingService.getRouteParams();

            ctx.governanceService = GovernanceService;
            ctx.oldFileId = null;
            if (ctx.currentInsight == null) {
                ctx.currentInsight = new GovernanceInsightDto();
                var dt = new Date();
                ctx.currentInsight.publicationDate = ('0' + (dt.getMonth() + 1)).slice(-2) + "/" + ('0' + dt.getDate()).slice(-2) + "/" + dt.getFullYear();
            }
            if (ctx.currentInsight != null && ctx.currentInsight.fileName != null) {
                ctx.oldFileName = ctx.currentInsight.fileName.toString();
                ctx.oldFileId = ctx.currentInsight.fileId;
            }
            ctx.isSaveDisabled = false;
        }

        public cancel = function () {
            var ctx = this;
            ctx.$modalInstance.close({ companyProfile: ctx.companyProfile });
        };

        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjectsAdmin.getMessageByInternalCode(code);
            ctx.notificationFactory.error('', msg);
        }

        // report upload
        public onSelectPdf(files, insight, companyProfile): any {
            var ctx = this;
            ctx.isSaveDisabled = true;
            ctx.currentInsight = insight;
            var file = files[0]; // html assures is just 1
            if (file) {
                if (file.size > 10 * 1024 * 1024 || file.type != "application/pdf") {
                    ctx.showErrorCode(2108);
                    ctx.isSaveDisabled = false;
                }
                else {
                    ctx.selectedFile = file;
                    var promise = ctx.governanceService.fileUploadReportFile(ctx.selectedFile, ctx.companyProfile.id.replace(" ", ""), "2", ctx.oldFileId);
                    promise.then(
                        //success
                        (data: { fileId: string; filename: string }) => {
                            ctx.$scope.$evalAsync(() => {
                                ctx.currentInsight.fileId = data.fileId;
                                //ctx.currentInsight.fileUrl = data.fileUrl;
                                ctx.newFileName = data.filename;
                                ctx.currentInsight.fileName = null;
                                ctx.notificationFactory.success('Upload succeeded.');
                                ctx.isSaveDisabled = false;
                            });
                        },
                        //error
                        () => {
                            ctx.showErrorCode(2114);
                            ctx.currentInsight.fileName = ctx.oldFileName;
                            ctx.isSaveDisabled = false;
                        }
                        );
                }
            }
        }

        public saveInsight(insight: GovernanceInsightDto) {
            var ctx = this;
            var addInsight = true;

            var message = ctx.validateInsight(insight);

            if (message == "") {
                // search insight
                if (ctx.companyProfile.insights != null) {
                    for (var i = 0; i < ctx.companyProfile.insights.length; i++) {
                        if (ctx.companyProfile.insights[i].id == insight.id) {
                            ctx.companyProfile.insights[i] = insight;
                            ctx.companyProfile.insights[i].fileName = ctx.newFileName;
                            ctx.companyProfile.insights[i].companyId = ctx.companyProfile.id;
                            addInsight = false;
                        }
                    }
                } else {
                    ctx.companyProfile.insights = new Array<GovernanceInsightDto>();
                }

                if (addInsight) {
                    insight.fileName = ctx.newFileName;
                    insight.companyId = ctx.companyProfile.id;
                    ctx.companyProfile.insights.push(insight);
                }

                // save insight
                var saveInsightPromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.saveInsight(insight, ctx.companyProfile.companyName);

                saveInsightPromise.then(function (corpData) {
                    ctx.companyProfile = corpData['data'];
                });

                saveInsightPromise.finally(function () {
                    ctx.cancel();
                    ctx.notificationFactory.success("Save operation executed successfully.");
                });
            }
            else {
                ctx.notificationFactory.error('', message);
            }
        }

        private validateInsight(insight: GovernanceInsightDto) {
            var ctx = this;

            var message = "";
            if (insight == null) {
                message += "Please check the following field(s): " + "<br/> Publication date" + "<br/> Title";
                if (ctx.selectedFile == null)
                    message += "<br/> Pdf file";
            }
            else if (insight.publicationDate == null ||
                insight.title == null ||
                (ctx.selectedFile == null && insight.fileId == null)) {
                message += "Please check the following field(s): ";

                if (insight == null || insight.publicationDate == null)
                    message += "<br/> Publication date";
                if (insight == null || insight.title == null)
                    message += "<br/> Title";
                if (ctx.selectedFile == null && insight.fileId == null)
                    message += "<br/> Pdf file";
            }
            else {
                if (insight.title.length > 100) {
                    message += "The title should have maximum 100 characters."
                }
            }
            return message;
        }

    }


    export var insightAddControllerName = 'InsightAddController';

    var mod = angular.module(governanceAdminReportsModuleName);

    mod.controller(insightAddControllerName,
        ['$scope', '$modal', '$modalInstance', 'notificationFactory', 'staticObjectsAdmin', 'RoutingService', 'currentInsight',
            'companyProfile', 'companyName', 'GovernanceService', InsightAddController]);
}